﻿<%@ WebHandler Language="C#" Class="Assesment.Web.AjaxHandler.Authentication.loginhandler" %>

using System;
using System.Web;
using System.Web.Security;

using System.Linq;

using Assesment.Library.DomainObject.Administration.UserManagement;
using Assesment.Library.DataAccess.Administration.UserManagement;
//using Assesment.Library.DataAccess.Transaction;
//using Assesment.Library.DomainObject.Administration.Catalog;
////using Assesment.Library.DomainObject.Transaction;
//using Assesment.Library.DataAccess.Administration.Catalog;

using System.Text;
using System.Configuration;

using System.Collections.Generic;
using Newtonsoft.Json.Linq;

using System.Web.SessionState;

using Assesment.Web;
using Assesment.Web.Support;

namespace Assesment.Web.AjaxHandler.Authentication
{
    public class loginhandler : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);

            string jsonString = string.Empty;
            jsonString = context.Server.UrlDecode(sr.ReadToEnd());
            JObject jO = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);

            sr.Close();
            sr.Dispose();

            string username = (string)jO["UserCode"];
            string password = (string)jO["Password"];
           

            bool isPersistent = (string)jO["Password"] == "true" ? true : false;
            string message = "Kode atau sandi anda salah!";

            recUser user = null;
            string url = FormsAuthentication.DefaultUrl;
            bool isValid = false;

            try
            {
                //if (Helper.HashCaptcha(captcha).Equals(captchaHash) && (!isExpired)) // Check input captcha = Generated captcha and captcha not expired
                //{
                    Assesment.Web.Support.Membership membership = new Assesment.Web.Support.Membership(ConfigurationManager.ConnectionStrings["AssesmentConn"].ConnectionString);
                    isValid = (membership.ValidateUser(username, password, out user));
                    if (isValid == true) // cek apakah usrname dan pass valid
                    {
                        if (user.IsActive == false)
                        {
                            isValid = false;
                            message = "User yang digunakan tidak aktif";
                        }
                        else if (user.IsForgotPass == true)
                        {
                            //recParameterRepo recParameterDal = new recParameterRepo(ConfigurationManager.ConnectionStrings["AssesmentConn"].ConnectionString);
                            //recParameter Password = recParameterDal.GetById("PWD");
                            //string HasPassword = Helper.CreatePasswordHash(Assesment.Web..GeneratePassword(5,0);
                            //if (password.ToUpper() == HasPassword)
                            //{
                            url += "?forgotpassword=true";
                            //}
                            user.IsForgotPass = false;
                            recUserRepo recUserDal = new recUserRepo(ConfigurationManager.ConnectionStrings["AssesmentConn"].ConnectionString);
                            recUserDal.Update(user);
                        }
                    }

              

            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            finally
            {

                if (isValid)
                {
                    string userData = string.Empty;
                    //bool isIndividual = false;
                    
                    // UserData format -> UserID | PositionID |  DepartmentID 
                    userData = user.UserID.ToString() + "|" + "1" + "|" + "1";


                    //PositionRepo PositionDal = new PositionRepo(ConfigurationManager.ConnectionStrings["AssesmentConn"].ConnectionString);

                    //List<Position> objByDept = PositionDal.GetListByDepartmentID(user.DepartmentID);
                    
                   
                    // Create a new ticket for user that has been authenticated.                    
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                        user.UserName,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(20),
                        isPersistent,
                        userData,
                        FormsAuthentication.FormsCookiePath);

                    // Create the cookie.
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
                    cookie.Value = FormsAuthentication.Encrypt(ticket);
                    cookie.Expires = ticket.Expiration;
                    context.Response.Cookies.Add(cookie);

                    context.Session["UserLoggedIn"] = user.UserName;

                }
            }

            string app = "http://" + context.Request.Url.Host + ":" + context.Request.Url.Port.ToString();

            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.AppendFormat("  {0}DefaultUrl{0}:{0}{1}{0}", "\"", app + url);
            sb.Append(",");
            sb.AppendFormat("  {0}IsValid{0}:{0}{1}{0}", "\"", isValid);
            sb.Append(",");
            sb.AppendFormat("  {0}Message{0}:{0}{1}{0}", "\"", message);
            sb.Append("}");

            context.Response.Write(sb.ToString());

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private bool IsAlreadyConnected(string userName, HttpContext context)
        {
            List<string> users = context.Application["UsersLoggedIn"] as List<string>;
            if (users != null)
            {
                lock (users)
                {
                    if (users.Contains(userName))
                    {
                        return true;
                    }
                    users.Add(userName);
                }

                context.Application["UsersLoggedIn"] = users;
            }
            context.Session["UserLoggedIn"] = userName;
            return false;
        }

    }

}